package com.ycfmedical.bed.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.R;
import com.ycfmedical.bed.base.BaseMenuActivity;
import com.ycfmedical.bed.service.BluetoothLeService;
import com.ycfmedical.bed.service.SampleGattAttributes;
import com.ycfmedical.bed.utils.ConvertOrderCheckoutUtil;
import com.ycfmedical.bed.utils.RefreshDataUtils;
import com.ycfmedical.bed.utils.ServerControl;
import com.ycfmedical.bed.wifi.WifiEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.router.Router;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 连接蓝牙并显示体重参数界面 Created by Administrator on 2017-03-29.
 */

public class BodyWeightShowActivity extends BaseMenuActivity
{
    
    private final static String TAG = BodyWeightShowActivity.class.getSimpleName();
    
    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
    
    int UUID_answer = 0;
    
    @BindView(R.id.bodyweight_connect)
    Button bodyweightConnect;
    
    @BindView(R.id.bodyweight_back)
    Button bodyweightBack;
    
    private TextView mConnectionState;
    
    private TextView mDataField;
    
    private String mDeviceName;
    
    private String mDeviceAddress;
    
    boolean a = false; // 确认是最后的测量值
    
    private ExpandableListView mGattServicesList;
    
    private BluetoothLeService mBluetoothLeService;
    
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
        new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    
    private boolean mConnected = false;
    
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    
    private final String LIST_NAME = "NAME";
    
    private final String LIST_UUID = "UUID";
    
    @Override
    public void initData(Bundle savedInstanceState)
    {
        
        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        // mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
        mDeviceAddress = "EC:24:B8:31:12:60";
        mGattServicesList = (ExpandableListView)findViewById(R.id.gatt_services_list);
        mGattServicesList.setOnChildClickListener(servicesListClickListner);
        mDataField = (TextView)findViewById(R.id.data_value);
        // getActionBar().setTitle(mDeviceName);
        // getActionBar().setDisplayHomeAsUpEnabled(true);
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); // 自动连接
    }
    
    @Override
    protected void onResume()
    {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (mBluetoothLeService != null)
        {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }
    
    @Override
    protected void onPause()
    {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }
    
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }
    
    @Override
    public int getLayoutId()
    {
        return R.layout.activity_bodyweightshow;
    }
    
    @Override
    public Object newP()
    {
        return null;
    }
    
    public static void launch(Activity activity)
    {
        
        Router.newIntent(activity).requestCode(Constants.RESULT_WEIGHT).to(BodyWeightShowActivity.class).launch();
    }
    
    private final ServiceConnection mServiceConnection = new ServiceConnection()
    {
        
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service)
        {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder)service).getService();
            if (!mBluetoothLeService.initialize())
            {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            mBluetoothLeService.connect(mDeviceAddress);
        }
        
        @Override
        public void onServiceDisconnected(ComponentName componentName)
        {
            mBluetoothLeService = null;
        }
    };
    // Handles various events fired by the Service.
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device. This can be a
    // result of read
    // or notification operations.
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action))
            {
                mConnected = true;
                invalidateOptionsMenu();
                if (mGattCharacteristics != null)
                {
                    // 连接蓝牙体重秤
                    connnetview();
                }
            }
            else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action))
            {
                mConnected = false;
                invalidateOptionsMenu();
                clearUI();
            }
            else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action))
            {
                // Show all the supported services and characteristics on the
                // user interface.
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
                
            }
            else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action))
            {
                // 判断设备是否为指定设备
                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }
        }
    };
    
    public void connnetview()
    {
        getDataThread dataThread = new getDataThread();
        dataThread.start();
    }
    @OnClick({R.id.bodyweight_connect, R.id.bodyweight_back})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.bodyweight_connect:

                break;
            case R.id.bodyweight_back:
                finish();
                break;
        }
    }
    
    private class getDataThread extends Thread
    {
        int flag = 0;
        
        @Override
        public void run()
        {
            while (UUID_answer == 0)
            {
                flag++;
                Log.e("TRY BLE", "TRY BLE");
                try
                {
                    XLog.e("SJH", "连接数量：" + mGattCharacteristics.size() + "flag值：" + flag);
                    final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(3).get(5);// 连接通信UUID口
                    mBluetoothLeService.setCharacteristicNotification(characteristic, true);
                    mBluetoothLeService.readCharacteristic(characteristic);
                    UUID_answer = 1;
                }
                catch (Exception e)
                {
                    Log.e("获取UUID失败", "111 + " + UUID_answer);
                    Log.e("mBluetoothLeService", "" + mBluetoothLeService);
                    if (mBluetoothLeService != null)
                        UUID_answer = 0;
                }
                if (flag >= 50000)
                {
                    UUID_answer = 1;
                    setData("蓝牙未连接上，是否重新连接");
                }
                
            }
            
        }
    }
    
    private final ExpandableListView.OnChildClickListener servicesListClickListner =
        new ExpandableListView.OnChildClickListener()
        {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                long id)
            {
                if (mGattCharacteristics != null)
                {
                    final BluetoothGattCharacteristic characteristic =
                        mGattCharacteristics.get(groupPosition).get(childPosition);
                    Log.i("选项", groupPosition + "---" + childPosition);
                    final int charaProp = characteristic.getProperties();
                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0)
                    {
                        if (mNotifyCharacteristic != null)
                        {
                            mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, false);// 接收数据
                            mNotifyCharacteristic = null;
                        }
                        mBluetoothLeService.readCharacteristic(characteristic);
                    }
                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0)
                    {
                        mNotifyCharacteristic = characteristic;
                        mBluetoothLeService.setCharacteristicNotification(characteristic, true);
                    }
                    return true;
                }
                return false;
            }
        };
    
    private void clearUI()
    {
        mGattServicesList.setAdapter((SimpleExpandableListAdapter)null);
    }
    
    private void updateConnectionState(final int resourceId)
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                System.out.println("ResourceId##########" + resourceId);
                mConnectionState.setText(resourceId);
            }
        });
    }
    
    private void displayData(String data)
    {
        XLog.e("SJH", "体重：" + data);
        if (data.equals("00000000000000000000100000c501804400"))
        {
            showDialog("体重测试失败，是否重新测试");
        }
        else
        {
            if (data != null)
            {
                System.out.println("DATA##########" + data);
                if (!a)
                {
                    String msg = data.substring(0, 28);
                    Log.e("data len", "" + data.length());
                    String data_t = data.substring(28, 32);
                    int weightData = hexstringtoint(data_t);
                    
                    // 设置数据
                    String bodyWeightTest = "" + weightData / 10 + "." + weightData % 10;
                    int bodyWeightValue = weightData*10;
                    mDataField.setText(bodyWeightTest);
                    if (msg.equals("100000c50c84ca10070001000001"))
                    {
                        a = true;
                        int bodyWeightCure = weightData * 10;
                        SendMsgAndSaveWeightData(bodyWeightCure, mDeviceAddress);
                        // 传输数据到页面
                        RefreshDataUtils refreshDataUtils = RefreshDataUtils.getRefreshDataUtils();
                        refreshDataUtils.setData(Constants.BED_WEIGHT, bodyWeightTest);
                        mDataField.setTextColor(Color.rgb(127, 255, 0));
                        //保存体重数据
                        saveBodyValue(bodyWeightCure);
                    }
                }
            }
        }
    }

    private void saveBodyValue(int weightValue)
    {
        // 保存数据到服务器
        ServerControl.SaveTmeAndWeight(weightValue + "", mDeviceAddress);
    }

    public int hexstringtoint(String i)
    {
        int resu = 0;
        byte[] b = new byte[2];
        b = hexStringToBytes(i);
        resu = bytetoint(b[0]) * 256 + bytetoint(b[1]);
        return resu;
    }
    
    public int bytetoint(byte i)
    {
        int m = i;
        m = i & 0xff;
        return m;
    }
    
    private static byte[] hexStringToBytes(String hexString)
    {
        if (hexString == null || hexString.equals(""))
        {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++)
        {
            int pos = i * 2;
            d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    
    private static byte charToByte(char c)
    {
        return (byte)"0123456789ABCDEF".indexOf(c);
    }
    
    private void displayGattServices(List<BluetoothGattService> gattServices)
    {
        if (gattServices == null)
            return;
        String uuid = null;
        String unknownServiceString = "未知设备";
        String unknownCharaString = "未知特征";
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData =
            new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
        
        for (BluetoothGattService gattService : gattServices)
        {
            HashMap<String, String> currentServiceData = new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);
            
            ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();
            
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics)
            {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }
        
        SimpleExpandableListAdapter gattServiceAdapter =
            new SimpleExpandableListAdapter(this, gattServiceData, android.R.layout.simple_expandable_list_item_2,
                new String[] {LIST_NAME, LIST_UUID}, new int[] {android.R.id.text1, android.R.id.text2},
                gattCharacteristicData, android.R.layout.simple_expandable_list_item_2,
                new String[] {LIST_NAME, LIST_UUID}, new int[] {android.R.id.text1, android.R.id.text2});
        mGattServicesList.setAdapter(gattServiceAdapter);
    }
    
    private static IntentFilter makeGattUpdateIntentFilter()
    {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }
    
    private void SendMsgAndSaveWeightData(int Value, String Mac)
    {
        String weightData = ConvertOrderCheckoutUtil.integerC10T16(Value);
        for (int i = weightData.length(); i < 4; i++)
        {
            weightData = "0" + weightData;
        }
        // 传递信息到护士站
        String OrderMsg =
            Constants.fhHeader + "64" + "0026" + weightData + "00000000000000000000000000" + Constants.bedId + "00";
        int length = OrderMsg.length();
        WifiEvent wifi = WifiEvent.getInstance();
        wifi.senddata(OrderMsg);
        // 保存数据到服务器
        ServerControl.SaveTmeAndWeight(weightData, Mac);
    }
    
    private void showDialog(String data)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(data);
        builder.setTitle("提示：");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                setResult(Constants.RESULT_WEIGHT);
                dialog.dismiss();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                
                dialog.dismiss();
            }
            
        });
        builder.create().show();
        
    }
    
    private void setData(String data)
    {
        Observable.create(new Observable.OnSubscribe<String>()
        {
            @Override
            public void call(Subscriber<? super String> subscriber)
            {
                subscriber.onNext(data);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.immediate()).subscribe(
            new Subscriber<String>()
            {
                @Override
                public void onCompleted()
                {
                    // 先判断再解除绑定
                    if (isUnsubscribed())
                    {
                        unsubscribe();
                    }
                }
                
                @Override
                public void onError(Throwable e)
                {
                    XLog.e("SJH", e.toString());
                }
                
                @Override
                public void onNext(String s)
                {
                    showDialog(s);
                }
            });
    }
    
}
